import Vue from 'vue'
import VueRouter from 'vue-router'
import axios from 'axios'
import store from "../store/index"


Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: ()=>import('../views/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: ()=>import('../views/Register.vue')
  },
  {
    path: '/admin',
    name: 'Admin',
    component: ()=>import('../views/Admin.vue'),
    children:[
      {
        path: 'postedit',     
        component: ()=>import('../views/PostEdit.vue')
      },
      {
        path: 'postadd',
        component: ()=>import('../views/PostAdd.vue')
      },
      {
        path: 'postupdate/:id',       
        component: ()=>import('../views/PostUpdate.vue'),
        props:true
      },
      {
        path: 'finduser',       
        component: ()=>import('../views/findUser.vue')
      },
      {
        path: 'searchuser',       
        component: ()=>import('../views/searchUser.vue')
      },
      {
        path: 'sendmsg',       
        component: ()=>import('../views/SendMsg.vue')
      },

      {
        path: '' ,   component: ()=>import('../views/Home.vue')
      }
    ]
  },
  {
    path: '/*',
    redirect:'/login'
  },
 
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

//路由守卫

router.beforeEach((to,from,next)=>{
  if(to.path == '/login' || to.path == '/register'){
    next();
  }else{
    axios.get('/api/cmsusers/info').then((res)=>{
      // console.log(res.data,123);
      if(res.data.code == 0){
        //发送事件  用store 传递用户名
        store.commit('set_username',res.data.userName);
        next();
      }else{
        next('/login')
      }
    }).catch(()=>{
      next('/login');
    })
  }
})

//同页面多个路由 显示报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
    if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
    return originalPush.call(this, location).catch(err => err)
}

export default router
